package charazay.tool.managers.site;


import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

import javax.swing.JOptionPane;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

import charazay.tool.cobjects.Player;
import charazay.tool.managers.XML.PlayerContentHandler;
import charazay.tool.managers.XML.PlayerXMLWriter;
import charazay.tool.managers.site.GenericSiteManager;
import charazay.tool.misc.Session;

public class PlayerSiteManager extends GenericSiteManager {

	int teamID = 0;

	
	public PlayerSiteManager(int teamID) {
		this.teamID = teamID;
	}
	
	public HashMap request(String username, String password) {
		String request_url = buildURL(username, password, String.valueOf(PLAYERS_LIST), String.valueOf(teamID) );
		XMLReader saxReader = null;
		HashMap players = null;
		try {
			saxReader = XMLReaderFactory.createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
			saxReader.setContentHandler(new PlayerContentHandler(username, password));
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			saxReader.parse(request_url);
			players = ((PlayerContentHandler)saxReader.getContentHandler()).getPlayerMap();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String errorMessage = ((PlayerContentHandler)saxReader.getContentHandler()).getError();
		if (errorMessage == null) {
			return players;
		}
		else {
			Session.username = null;
			Session.password = null;
			JOptionPane.showMessageDialog(null, errorMessage);
			return null;
		}
		
	}
	
	public void compareAndSave(HashMap players) {
		for (Iterator<Integer> It = players.keySet().iterator(); It.hasNext();) {
			Integer player_id = (Integer) It.next();
			Player currentPlayer = (Player) players.get(player_id);
			PlayerXMLWriter xmlwriter = new PlayerXMLWriter(currentPlayer);
			xmlwriter.write();
		}
	}
}
